<template>
  <Modal
    width="532"
    style="{margin-top:10px}"
    :closable="false"
    :mask-closable="false"
    v-model="modAvatar"
  >
    <spin v-show="featureLoading" size="large" fix></spin>
    <a class="ivu-modal-close" @click="modAvatar = false">
      <Icon type="ios-close-empty"></Icon>
    </a>
    <div slot="header" class="ivu-modal-header-inner">修改【{{modAvatarInfo.user_name}}】的人脸特征</div>
    <Row v-if="modUpload">
      <uploader
        :count="uploadedAvatarRegsLength"
        :maxlength="FEATURE_MAX"
        @fileChange="handleUserAvatarRegUpload"
        @fileAdd="handleUserAvatarRegAdd"
      >
        <!-- Uploader的标题slot -->
        <span slot="title">上传特征</span>
        <!-- 需要预览时，增加UploaderFiles容器 -->
        <uploaderfiles slot="uploader-files">
          <uploaderfile
            v-for="(imgSrc,i) in uploadedAvatarRegs"
            :key="i"
            :image-url="createSnapshot(imgSrc)"
            @click="handleUserAvatarRegRemove(imgSrc)"
          ></uploaderfile>
        </uploaderfiles>
      </uploader>
    </Row>
    <Row type="flex" justify="start" v-else>
      <img
        v-for="(imgSrc,i) in modAvatarInfo.avatarReg"
        :key="i"
        style="width:80px;height:80px;margin:10px;object-fit: cover;cursor: pointer;"
        :src="imgSrc"
        @click="handleShowUserAvatarReg(i,modAvatarInfo.avatarReg.length,imgSrc)"
      >
    </Row>
    <div slot="footer" v-if="modUpload">
      <Button type="primary" size="large" @click="uploadUserAvatarReg(modAvatarInfo.user_id)">确认上传</Button>
    </div>
    <div slot="footer" v-else>
      <Button
        type="error"
        size="large"
        @click="handleDelAllFeature(modAvatarInfo.user_id, modAvatarInfo.user_name)"
      >全部删除</Button>
      <Button type="primary" size="large" @click="modUpload=true">重新上传</Button>
    </div>
  </Modal>
</template>
<script>
import Uploader from "../../../views/weiget/uploader.vue";
import Uploaderfile from "../../../views/weiget/uploader-file.vue";
import Uploaderfiles from "../../../views/weiget/uploader-files.vue";
import ImageUtils from "@/libs/image.js";
// import HorizonUploader from "../components/HorizonUploader.vue";
// import DownloadTableModal from "./DownloadTableModal.vue";
// import UploadFeatureModal from "./UploadFeatureModal.vue";

import Tool from "@/libs/util";
import { getFeature, regFeature, delFeature } from "../../../controllers/user";
import _ from "lodash";
import Constant from "../../../libs/constants";

export default {
  name: "add-feature",
  created() {},
  computed: {
    uploadedAvatarRegsLength: function() {
      return this.uploadedAvatarRegs.length;
    }
  },
  components: {
    Uploader,
    Uploaderfile,
    Uploaderfiles
  },
  data() {
    return {
      FEATURE_MAX: Constant.FEATURE_MAX,
      show: false,
      modAvatarInfo: {
        user_id: "",
        user_name: "",
        avatarReg: []
      },
      uploadedAvatarRegs: [],
      featureLoading: false,
      modUpload: false,
      modAvatar: false
    };
  },
  methods: {
    handleSubmit() {
      this.show = false;
    },
    handleUserAvatarRegRemove(item) {
      // 从 upload 实例删除数据
      this.uploadedAvatarRegs.splice(this.uploadedAvatarRegs.indexOf(item), 1);
    },
    createSnapshot(item) {
      return "data:image/" + item.type + ";base64," + item.picdata;
    },
    handleUserAvatarRegAdd(img, width, height) {
      if (["image/jpg", "image/jpeg", "image/png"].indexOf(img.type) < 0) {
        return false;
      }
      if (this.uploadedAvatarRegsLength >= this.FEATURE_MAX) {
        return false;
      }
      let name = img.name;
      if (width < this.IMG_WIDTH_MIN || width > this.IMG_WIDTH_MAX) {
        let errMsg =
          "图片" +
          name +
          "宽度存在问题，应在(" +
          this.IMG_WIDTH_MIN +
          "-" +
          this.IMG_WIDTH_MAX +
          ")之间";
        this.$Message.error(errMsg);
        return;
      } else if (height < this.IMG_HEIGHT_MIN || height > this.IMG_HEIGHT_MAX) {
        let errMsg =
          "图片" +
          name +
          "高度存在问题，应在(" +
          this.IMG_HEIGHT_MIN +
          "-" +
          this.IMG_HEIGHT_MAX +
          ")之间";
        this.$Message.error(errMsg);
        return;
      }
      const reader = new FileReader();
      let _this = this;
      reader.onload = function(e) {
        _this.uploadedAvatarRegs.push({
          picdata: e.target.result.split(",")[1],
          type: img.type.split("/")[1]
        });
      };
      reader.readAsDataURL(img);
    },
    handleShowUserAvatarReg(i, cnt, img) {
      this.imgSrc = "url(" + img + ")";
      this.previewImgInfo.currentIndex = i;
      this.previewImgInfo.total = cnt;
      this.featureModal = true;
    },
    handleUserAvatarRegUpload(imgs) {
      _.forEach(imgs, file => {
        if (["image/jpg", "image/jpeg", "image/png"].indexOf(file.type) < 0) {
          return false;
        }
        if (this.uploadedAvatarRegsLength >= this.FEATURE_MAX) {
          return false;
        }

        // base64
        const reader = new FileReader();
        let _this = this;
        let name = file.name;
        reader.onload = function(e) {
          let img = new Image();
          img.onload = function() {
            let width = img.width;
            let height = img.height;
            if (width < _this.IMG_WIDTH_MIN || width > _this.IMG_WIDTH_MAX) {
              let errMsg =
                "图片" +
                name +
                "宽度存在问题，应在(" +
                _this.IMG_WIDTH_MIN +
                "-" +
                _this.IMG_WIDTH_MAX +
                ")之间";
              _this.$Message.error(errMsg);
            } else if (
              height < _this.IMG_HEIGHT_MIN ||
              height > _this.IMG_HEIGHT_MAX
            ) {
              let errMsg =
                "图片" +
                name +
                "高度存在问题，应在(" +
                _this.IMG_HEIGHT_MIN +
                "-" +
                _this.IMG_HEIGHT_MAX +
                ")之间";
              _this.$Message.error(errMsg);
            } else {
              _this.uploadedAvatarRegs.push({
                picdata: e.target.result.split(",")[1],
                type: file.type.split("/")[1]
              });
            }
          };
          img.src = e.target.result;
        };
        reader.readAsDataURL(file);
        return true;
      });
    },
    handleDelAllFeature(userId, userName) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除【" + userName + "】的特征库？",
        onOk: () => {
          delFeature({ user_id: userId }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.modAvatar = false;
            } else {
              this.$Message.error("删除失败!");
            }
          });
        }
      });
    },
    uploadUserAvatarReg(userId) {
      //检查待上传文件
      //组装上传信息
      //发起请求
      //处理上传过程
      //成功上传or错误
      //清除URL.revokeObjectURL(objectURL);//注销内存使用。

      // TODO
      if (this.uploadedAvatarRegsLength < this.FEATURE_MIN) {
        this.$Message.info("请选择特征图");
        return;
      }

      // 注册特征
      regFeature({
        user_id: userId,
        feature_pic: this.uploadedAvatarRegs
      }).then(res => {
        if (res.code === 0) {
          this.$Message.success("注册成功");
          this.modAvatar = false;
        }
      });
    },
    showModal(user) {
      this.show = true;
      this.uploadedAvatarRegs.splice(0, this.uploadedAvatarRegs.length);
      this.modAvatarInfo.user_id = user.user_id;
      this.modAvatarInfo.user_name = user.user_name;
      this.modAvatarInfo.avatarReg = [];

      this.featureLoading = true;
      this.modUpload = false;
      this.modAvatar = true;
      getFeature(user.user_id).then(res => {
        if (res.data && res.data.length > 0) {
          this.modAvatarInfo.avatarReg = _.map(
            res.data,
            i => "data:image/jpg;base64," + i
          );
          this.modUpload = false;
        } else {
          this.modUpload = true;
        }
        this.featureLoading = false;
      });
    }
  }
};
</script>